package com.sun.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.model.entity.Options;
import com.sun.model.entity.Subject;
import com.sun.preproces.SubjectPreprocessing;
import com.sun.service.subject.SubjectInfoService;

import com.until.controller.AbsController;
import com.until.pagination.PaginationRequest;
import com.until.request.ParamNotNull;
import com.until.response.AbsResponseBody;
import com.until.response.RestfulCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author AdminUser
 */
@RestController
@RequestMapping("/subject")
public class SubjectInfoController extends AbsController<Subject,Object,Integer, SubjectPreprocessing> {
    @ModelAttribute
    public SubjectPreprocessing init(@ModelAttribute PaginationRequest paginationRequest, @ModelAttribute Subject subject,
                                     @RequestParam(value = "action",required = false,defaultValue = "")String action) {
        SubjectPreprocessing preprocessing = new SubjectPreprocessing();
        preprocessing.setPaginationRequest(ParamNotNull.objCheckIsNull(paginationRequest)?new PaginationRequest(1,5):paginationRequest);
        preprocessing.setSubject(ParamNotNull.objCheckIsNull(subject)?new Subject():subject);
        preprocessing.setAction(action);
        return preprocessing;
    }

    @Autowired
    private SubjectInfoService subjectInfoService;

    @GetMapping("")
    @Override
    public Object all(SubjectPreprocessing page) throws Exception {
        PageHelper.startPage(page.getPaginationRequest().getPageNumber(), page.getPaginationRequest().getPageSize());
        RestfulCode.CodeSatCode getPage;
        try {
            // todo 根据请求动作得到结果
            getPage=RestfulCode.getSuccessResult(new PageInfo<>(subjectInfoService.coreSelection(page.getSubject(), page.getAction(), HttpMethod.GET)));
        } catch (Exception e) {
            getPage=RestfulCode.getSuccessResult(new PageInfo<>(subjectInfoService.getAllList()));
        }
        return JSON.toJSON(getPage);
    }

    @PostMapping("")
    @ResponseBody
    public RestfulCode.CodeSatCode add(@RequestParam Subject subject,@RequestParam List<Options> options) throws Exception {
        int i = subjectInfoService.insertObject(subject, options);
        RestfulCode.CodeSatCode codeSatCode = i > 0 ? AbsResponseBody.USER_OPERATION_SUCCEEDED : AbsResponseBody.USER_ACTION_FAILED;
        return RestfulCode.getSuccessResult(codeSatCode.getFlagCode(),codeSatCode.getMessage());
    }
}
